package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.TaskDto;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.service.TaskService;
import com.heima.wemedia.service.WmAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * @author jack
 * @data 2023 11:36
 */
@Service
@Slf4j
public class TaskServiceImpl implements TaskService {
    @Autowired
    private IScheduleClient iScheduleClient;
    @Autowired
    private WmAutoScanService wmAutoScanService;
    /**
     * 远程调用延迟微服务，进行审核文章任务添加
     *
     * @param wmNews
     */
    @Override
    public void addTask(WmNews wmNews) {
        TaskDto dto = new TaskDto();
        dto.setExecuteTime(wmNews.getPublishTime().getTime());
        dto.setParameters(String.valueOf(wmNews.getId()).getBytes(StandardCharsets.UTF_8));
        dto.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType()); //1001
        dto.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority()); //1
        iScheduleClient.addTask(dto);
    }

    /**
     * 定义从schedule中拉取审核文章任务，一旦拉到数据，就立刻消费
     * 任务执行频次：每秒执行一次
     */
    @Override
    @Scheduled(cron = "* * * * * ?")
    public void pullTask() {
        ResponseResult result = iScheduleClient.pullTask(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if (result.getCode().equals(200)){
            Integer newsId = Integer.valueOf(result.getData().toString());
            log.info("==============拉取审核文章任务成功,开始审核文章：{}=================",newsId);

            //审核文章
            wmAutoScanService.scanNews(newsId);
        }
    }
}
